﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace UI.Helper
{
    public static class Utils
    {
        public static string IncludeCSS(this HtmlHelper html, string cssFile)
        {
            string cssPath = cssFile.Contains("~") ? cssFile : ("~/content/" + cssFile);
            string url = html.ResolveUrl(cssPath);
            return string.Format("<link type=\"text/css\" rel=\"stylesheet\" href=\"{0}\" />\n", url);
        }
        public static string IncludeJS(this HtmlHelper html, string jsFile)
        {
            string jsPath = jsFile.Contains("~") ? jsFile : ("~/scripts/" + jsFile);
            string url = html.ResolveUrl(jsPath);
            return string.Format("<script type=\"text/javascript\" src=\"{0}\" ></script>\n", url);
        }
        public static string ResolveUrl(this HtmlHelper html, string relativeUrl)
        {
            if (relativeUrl == null)
                return null;
            if (!relativeUrl.StartsWith("~"))
                return relativeUrl;
            return (html.ViewContext.HttpContext.Request.ApplicationPath + relativeUrl.Substring(1)).Replace("//", "/");
        }

        public static string IncludeImage(this UrlHelper url, string imageName)
        {
            return url.Content("~/Images/" + imageName);
        }

        public static string Substring(string content, int length)
        {
            if (content.Length > length)
            {
                var endPosition = content.IndexOf(" ");
                while (endPosition < length - 1)
                {
                    var tmp = content.IndexOf(" ", endPosition + 1);
                    if (tmp < length - 1)
                        endPosition = tmp;
                    else
                        break;
                }
                content = content.Substring(0, endPosition);
            }

            return content;
        }
    }
}